package cn.tedu.v2_3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.util.Scanner;
/**

 *        练习：1.Client 添加IP  功能
 *             2.Server  关闭通讯\代码简介，写Client关闭通讯、代码简洁
 */
public class Client {
    private Socket socket;

    public Client() {

            try {
                socket = new Socket("172.20.17.9", 6666);

            } catch (NullPointerException e) {
                System.out.println("友情提示：IP传入错误导致链接失败~");
            } catch (UnsupportedEncodingException e) {
                System.out.println("友情提示：IP传入错误");
            } catch (ConnectException e) {
                System.out.println("客户端链接失败：建议检查IP或者端口号");
            } catch (IOException e) {
                System.out.println("客户端链接服务器失败，提示：检查IP/端口");
            }
        }
        public void start () {

            PrintWriter pw = null;

            try {

                OutputStream os = socket.getOutputStream();
                InputStream is = socket.getInputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8");

                InputStreamReader isr = new InputStreamReader(is, "UTF8");

                BufferedWriter bw = new BufferedWriter(osw);

                BufferedReader br = new BufferedReader(isr);

                pw = new PrintWriter(bw, true);
                System.out.println("对服务器端说话：");
                Scanner input = new Scanner(System.in);
                String line = null;
                while (true) {
                    line = input.nextLine();
                    pw.println(line);
                    System.out.println("写出成功~");
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println("客户端/服务器端编码集有问腿！");
            } catch (IOException e) {
                System.out.println("客户端链接服务器端：IO流操作出现错误！");
            } finally {

                if (socket != null && !socket.isClosed()) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("客户端关闭失败");
                    }
                }
            }
        }
        public static void main (String[]args){
            Client client = new Client();
            client.start();
        }
    }

